import { createApp } from 'vue'
import App from './App.vue'

// import element-plus start
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
// import element-plus end


// import pinia start
import { createPinia } from 'pinia'
// import pinia end

// import router start
import router from './router/index'
// import router end

import { useAppStore } from '@/store/index'

const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

const pinia = createPinia()

app
  .use(pinia)
  .use(ElementPlus, {
    locale: zhCn,
  })
  .use(router)
  .mount('#app')
  .$nextTick(async () => {
    // 应用启动时验证登录状态
    await checkAuthStatus()
  })

// 检查登录状态
async function checkAuthStatus() {
  const appStore = useAppStore()
  const token = localStorage.getItem('authToken')
  
  const userService = (window as any).userService
  if (token && userService) {
    try {
      // 验证token是否有效
      const result = await userService.checkAuth(token)
      
      if (result.success && result.userInfo) {
        // token有效，更新用户信息
        appStore.login(result.userInfo)
        console.log('自动登录成功')
      } else {
        // token无效，清理状态
        console.log('Token已过期，清理登录状态')
        await appStore.logout()
      }
    } catch (error) {
      console.error('验证登录状态失败:', error)
      // 验证失败，清理状态
      await appStore.logout()
    }
  }
}
